#include "widget.h"
#include "ui_widget.h"
#include <QString>
#include <QPushButton>
#include <QDebug>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QJsonObject>
#include <QJsonDocument>
#include <QByteArray>

/* * * * * * * * * * * * * * * * * * * * * * * * * * * *
 *  @file:     widget.cpp
 *  @brief:    登录窗口
 *  @author:   caoshi
 *  @time:     2022-03-23 22:27:40
 * * * * * * * * * * * * * * * * * * * * * * * * * * * */
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    connect(ui->loginBtn, &QPushButton::clicked, this, &Widget::hadleLogin);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::hadleLogin() {
    qDebug() << "登录按钮被点击了开始发送http请求";

    QString nameText = ui->username->text();
    QString pwdText = ui->password->text();

    qDebug() << nameText;

    QNetworkAccessManager *accessManager = new QNetworkAccessManager(this);
    // 发送HTTP请求
    connect(accessManager, &QNetworkAccessManager::finished, this, &Widget::finishedSlot);
    // GET请求
    QNetworkRequest req;
//    req.setUrl(QUrl("http://localhost:8082/testqt/test1?username=" + nameText + "&pwd=" + pwdText));
//    accessManager->get(req);

    // POST请求 json数据传输
    req.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/json"));
    req.setUrl(QUrl("http://localhost:8082/testqt/test2"));

    QJsonObject loginParam;
    loginParam.insert("username", nameText);
    loginParam.insert("pwd", pwdText);

    QByteArray bytes = QJsonDocument(loginParam).toJson(QJsonDocument::Compact);
    QString str(bytes);

    qDebug() << str;
    accessManager->post(req, bytes);
	//////
	
}

void Widget::finishedSlot(QNetworkReply *reply)
{
    if (reply->error() == QNetworkReply::NoError) {
        QByteArray bytes = reply->readAll();
        qDebug() << QString("响应数据: ") + bytes;
    }
}


